const app = getApp();
const db = wx.cloud.database();
Page({
  data: {
    //支付状态为0，未支付为1，待发货为2，待收货为3
    address:0,
    state:0,
    orderList: [],
    total: 0,
    totalPrice: 0.0,
    cur: {},
    position: [
      { value: 'top', text: '顶部弹出' },
      { value: 'left', text: '左侧弹出' },
      { value: 'center', text: '中间弹出' },
      { value: 'bottom', text: '底部弹出' },
      { value: 'right', text: '右侧弹出' },
    ],
  },
  onShow() {
    this.updateOrderList();
  },
  // 更新订单列表  
  updateOrderList() {  
    // 从本地存储中获取总商品数量、总价格和订单列表
    const total = wx.getStorageSync('total');
    const totalPrice = wx.getStorageSync('totalPrice');
    const orderList = wx.getStorageSync('orderList') ;
    // 更新页面的订单列表、总商品数量和总价格  
    this.setData({
      orderList,
      total,
      totalPrice
    });
  },
  // 点击增加按钮
  plusClick(event) {
    const index = event.target.dataset.index;
    let orderList = this.data.orderList;
    ++orderList[index].number;
    this.setData({
      "orderList": orderList
    });
    this.totalize();
  },
  // 点击减少按钮
  reduceClick(event) {
    const index = event.target.dataset.index;
    let orderList = this.data.orderList;
    let goodNum = orderList[index].number;
    if (goodNum <= 0) {
      // 如果数量为 0，从购物车列表中删除该商品
      orderList.splice(index, 1);
    } else {
      --orderList[index].number;
    }
    this.setData({
      "orderList": orderList
    });
    this.totalize();
    // this.updateAllCheckedStatus();
  },
  // 结算函数
  totalize() {
    let orderList = this.data.orderList;
    let total = 0;
    let totalPrice = 0.0;
    for (let i = 0; i < orderList.length; i++) {
      let good = orderList[i];
      if (good.choose) {
        total = total + good.number;
        totalPrice = totalPrice + good.number * good.price;
      }
    }
    totalPrice = totalPrice.toFixed(2);
    this.setData({
      "total": total,
      "totalPrice": totalPrice
    });
  },
  async handlePopup(e){
  //   for(var i=0;i<this.data.orderList.length;i++){
  //     await db.collection('shop_order').add({
  //       data: {
  //         openid,
  //         this.data.orderList[i].cover,
  //         phoneNumer,
  //         avatarUrl,
  //         selectedRole
  //       }
  //     });
  //   }
  const orderList = this.data.orderList;
  const db = wx.cloud.database();
  const tasks = [];
  const res = await wx.cloud.callFunction({
    name: 'getOpenai'
  });
  const openid = res.result.openid;
  //遍历将订单商品加入数据库
  console.log(this.orderList)
  if(this.data.address==''){
    wx.showToast({
      title: '请完善地址信息',
      icon: 'none'
    });
    return
  }
  if(this.data.total==0){
    wx.showToast({
      title: '请至少选择一个商品',
      icon: 'none'
    });
    return
  }
      db.collection('shop_order').add({
        data: {
          name: this.data.name,
          phone: this.data.phone,
          address: this.data.address,
          openid: openid, // 根据实际情况设置 openid
          goods: orderList,
          state:1,
          total:this.data.total,
          totalPrice:this.data.totalPrice
        }
      }).then(res => {
        // res.data 包含该记录的数据
        console.log(res.data)
      })
  //弹出中间框
  const { item } = e.currentTarget.dataset;
      this.setData(
        {
          cur: item,
        },
        () => {
          this.setData({ visible: true });
        },
      );
   },
   onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
    });
  },
  //更新状态支付数据库，更新 shop_order 数据库中每个商品状态为 1
  async onClose() {
    // 更新 shop_order 数据库中每个商品状态为 1
    const orderList = this.data.orderList;
    const db = wx.cloud.database();
    const res = await wx.cloud.callFunction({
      name: 'getOpenai',
    });
    const openid = res.result.openid;
    const query = db
     .collection('shop_order')
     .where({ openid: openid });
    // const updateTasks = [];
    //更新状态支付数据库
    console.log(query);
    // for (const order of orderList) {
    //   updateTasks.push(
    //     query.where({ good_id:order.good_id }).update({
    //       data: {
    //         state: 1,
    //       },
    //     })
    //   );
    // }
    // try {
    //   await Promise.all(updateTasks);
    //   wx.showToast({
    //     title: '商品状态更新成功',
    //     icon: 'success',
    //   });
    // } catch (error) {
    //   wx.showToast({
    //     title: '商品状态更新失败',
    //     icon: 'none',
    //   });
    //   console.error(error);
    // }
    // console.log(query);
     //更新弹出框的关闭状态
     this.setData({
      visible: false,
    });
    wx.navigateBack({
      delta: 2
    })
  },
  // s实现选择收货地址函数
  addAddress() {  
    let that =this;
    wx.chooseAddress({  
      success: (result)=>{
        console.log(result)
        that.setData({
          phone: result.telNumber,
          name: result.userName,
          address: result.provinceName+result.cityName+result.detailInfo
        })
      },
    })
  }  
});
